/**
 * Created by baowenwu765 on 2017/9/4.
 * @description 存放培训点名ts
 */
import {Component, OnInit, ViewEncapsulation, ViewChild, OnDestroy} from '@angular/core';
import {ImageServeService} from '@shared/service/image/image-serve.service';
import {SeedInfiniteScroll} from '@shared/components/infinite-scroll/seed-infinite-scroll/seed-infinite-scroll.component';
import {Subject} from 'rxjs/Subject';
import {ActivatedRoute} from '@angular/router';
import {TrainService} from "@train/train.service";
import {ToolsService} from "@shared/service/tools/tools.service";
import {StudentScheduleCourseVO} from "@interface/index";


@Component({
  selector: 'seed-roll-call',
  templateUrl: './roll-call.component.html',
  styleUrls: ['./roll-call.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class RollCallComponent implements OnInit, OnDestroy {
  public allChose = false;   //  全选按钮状态
  public blurCheck = false;   //  失去焦点判断条件
  public disableAllChose = true;   //  禁止全选按钮
  public nodataMark = false;   //  没有数据标志
  public properties: string; // 次课状态   值为2  表示次课
  public choseMore = false;   //  多选
  public processor: boolean;
  public rollcallData: Array<StudentScheduleCourseVO> = [];   // 学员列表对象
  public curseParam: {
    classScheduleId?: number;
    teacherId?: number;
    search?: string;
    page?: number;
    rows?: number;
    courseName?: string
  } = {};    //  获取学员列表接口参数
  public operateParam: any = {
    status: 0,
    modifyId: '',
    idList: [],
  };   //  操作销课、撤销接口参数
  public operateName: any = [];  // 操作销课学员姓名
  public keyswords: string;  // 操作销课学员姓名
  @ViewChild(SeedInfiniteScroll) infiniteScroll;
  private subscription: Subject<void> = new Subject<void>();
  private searchTerms = new Subject<string>();
  public courseName: string;

  constructor(public imgService: ImageServeService,
              public trainService: TrainService,
              private tools: ToolsService,
              public route: ActivatedRoute) {
  }

  ngOnInit() {
    this.route.queryParams.subscribe(param => {
      const curseParam = this.curseParam;
      curseParam.classScheduleId = param['classScheduleId'];
      curseParam.page = 1;
      curseParam.rows = 10;
      curseParam.teacherId = param['teacherId'];
      this.courseName = param['courseName'];
      this.properties = param['properties'];
    });
    this.getRollCallList(this.curseParam);
    this.searchTerms.debounceTime(300).distinctUntilChanged().subscribe((value) => {
      this.realTimeGetInfo(value);
    });
  }

  /**
   * @description 获取图标
   * @param iconName 图标名
   * @author baoww765
   * @date 2018-01-02
   */
  getIcon(iconName: string) {
    return this.imgService.getIcon(iconName);
  }

  /**
   * @description 即时搜索
   * @author 鲍文武-765
   * @date 2017/09/20
   * @param search 搜索关键字
   */
  realTimeSearch(value: string) {
    this.searchTerms.next(value);
  }

  loseBlur() {
    this.blurCheck = false;
  }

  getFocus() {
    this.blurCheck = true;
  }

  realTimeGetInfo(keyswords) {
    this.curseParam.page = 1;
    this.rollcallData = [];
    this.curseParam.search = keyswords;
    this.getRollCallList(this.curseParam);
    this.blurCheck = true;
  }

  loadScrollList() {
    this.getRollCallList(this.curseParam);
  }

  /**
   * @description 获取学员列表
   * @author 鲍文武-765
   * @date 2017/09/20
   * @param curseParam 根据教师ID及班级信息查询学员列表，processor字段判断学员是否可做销课
   * 、撤销等操作，如为false，则不可进行操作及多选操作
   */
  getRollCallList(param) {
    this.trainService.getRollCallList(param).subscribe(res => {
      if (res.result === '0' && res.data.pageVo.list.length > 0) {
        this.curseParam.page++;
        if (this.infiniteScroll) {
          this.infiniteScroll.complete();
        }
        this.rollcallData = [...this.rollcallData, ...res.data.pageVo.list];
        this.processor = res.data.processor;
        this.nodataMark = false;
        if (!res.data.pageVo.hasNextPage && this.infiniteScroll) {
          this.infiniteScroll.enable(false);
        }
      } else {
        this.nodataMark = true;
      }
    });
  }

  /**
   * @description 多选操作
   * @author 鲍文武-765
   * @date 2017/09/20
   * @param processor 只有在学员可操作销课情况下才显示多选按钮
   */
  moreChose() {
    this.choseMore = !this.choseMore;
    this.disableAllChose = true;
    this.operateParam.idList = [];
    this.operateName = [];
    this.allChose = false;
    let count = 0;
    for (let item of this.rollcallData) {
      if (item.status !== 0) {
        count++;
      }
    }
    if (count === this.rollcallData.length) {
      this.disableAllChose = false;
    }
  }

  /**
   * @description 全选
   * @author 鲍文武-765
   * @date 2017/09/20
   * @param operateParam.idlist用于存储学员id，进入多选之后有学员可选时才能操作全选，否则置灰；
   * 若多选之后，没有任何学员被选中，则不显示销课
   */
  choseAll() {
    const rollcallData = this.rollcallData;
    this.operateParam.idList = [];
    this.operateName = [];
    this.allChose = !this.allChose;
    if (this.allChose) {
      // for (let item of this.rollcallData) {
      //   if (item.status === 1 || item.status === 3) {
      //     continue;
      //   }
      //   ;
      //   if (this.operateParam.idList.indexOf(item.id) === -1) {
      //     this.operateParam.idList.push(item.id);
      //     this.operateName.push(item.name);
      //   }
      // }
      for (let i = 0; i < rollcallData.length; i++) {
        if (rollcallData[i].status === 1 || rollcallData[i].status === 3 || rollcallData[i].freezeStatus === 1) {
          continue;
        }
        if (this.operateParam.idList.indexOf(rollcallData[i].id) === -1) {
          this.operateParam.idList.push(rollcallData[i].id);
          this.operateName.push(rollcallData[i].name);
        }
      }
    }
  }

  /**
   * @description 单选
   * @author 鲍文武-765
   * @date 2017/09/20
   * @param operateParam.idList用于存储学员id，用于操作销课、撤销；operateName用于在对话框中显示被选中学员姓名；
   * 取消选择某学员，则从上述参数中删除对应id及name
   */
  choseSingle(item) {
    if (item.status === 1 || item.status === 3 || item.freezeStatus === 1) { // freezeStatus=1 是冻结状态
      return;
    }
    if (this.operateParam.idList.indexOf(item.id) > -1) {
      this.operateParam.idList.splice(this.operateParam.idList.indexOf(item.id), 1);
      this.operateName.splice(this.operateParam.idList.indexOf(item.id), 1);
    } else {
      this.operateParam.idList.push(item.id);
      this.operateName.push(item.name);
    }
  }

  /**
   * @description 根据状态判断该学生当前考勤状态并显示
   * @author baoww765
   * @date 2018-01-04
   * @param status
   * */
  checkStatus(status) {
    switch (status) {
      case 1:
        return '已销课';
      case 3:
        return '已请假';
      case 2:
        return '缺勤';
    }
  }

  /**
   * @description 根据状态返回背景图片
   * @author baoww765
   * @date 2018-01-04
   * @param status
   * */
  bgImg(status, id) {
    if (status === 1 || status === 3) {
      return this.getIcon('disableSelect.png');
    } else if (this.operateParam.idList.indexOf(id) >= 0) {
      return this.getIcon('selected.png');
    } else {
      return this.getIcon('unselect.png');
    }
  }

  /**
   * @description 发起销课、撤销请求，根据所传status状态值进行对应操作
   * @author 鲍文武-765
   * @date 2017/09/20
   * @param operateParam.idList用于存储学员id，用于操作销课、撤销；operateName用于在对话框中显示被选中学员姓名
   */
  doAttendance(param, i, status) {
    let title = '';
    const nameArray = ['撤销', '销课', '', '请假'];
    title = nameArray[status];
    this.trainService.doAttendance(param).subscribe(res => {
      if (res.result === '0') {
        this.rollcallData[i].modifyTime = res.data;
        this.rollcallData[i].status = status;
        this.tools.showToast(`${title}成功`);
      } else {
        this.tools.showToast(`${title}失败`);
      }
    });
  }

  /**
   * @description 单个操作
   * @author baoww765
   * @date 2018-01-05
   * @param name,i,status,modifyId
   * */
  operateSingle(name, i, status, modifyId) {
    this.operateParam.status = status;
    this.operateParam.idList = [modifyId];
    const nameArray = ['撤销', '销课', '', '请假'];
    const title = nameArray[status];
    const that = this;
    this.tools.presentConfirm(`${title}学员: ${name} ?`, 1, function () {
      that.doAttendance(that.operateParam, i, status);
    });
  }

  /**
   * @description 根据状态判断是否显示分割线 processor状态判断是否可以操作，
   * choseMore判断是是否为多选状态
   * @author baoww765
   * @date 2018-01-05
   * @param status
   * */
  checkLine(status) {
    if (!this.choseMore && this.processor) {
      const value = parseInt(this.properties, 10);
      switch (status) {
        case 0:
        case 4:
          return value !== 2;
        case 1:
        case 3:
          return true;
        case 2:
          return value === 2;
        default :
          return false;
      }
    }
  }

  /**
   * @description 根据状态及是否是次课properties、是否多选状态choseMore判断是否显示请假
   * 次课状态下(properties=2)没有请假操作，正常课程下有请假操作
   * @author baoww765
   * @date 2018-01-05
   * @param status
   * */
  checkLeave(status) {
    if (parseInt(this.properties, 10) !== 2) {
      if (!this.choseMore && this.processor && (status === 0 || status === 4)) {
        return true;
      } else {
        return false;
      }
    } else {
      return false;
    }
  }

  /**
   * @description 批量操作销课
   * @author 鲍文武-765
   * @date 2017/09/20
   * @param operateParam.idList用于存储学员id，用于操作销课、撤销；operateName用于在对话框中显示被选中学员姓名
   */
  operateBatch(status) {
    if (this.operateParam.idList.length === 0) {
      return;
    }
    const showName = ['', '销课', '', '请假'];
    this.operateParam.status = status;
    const tipsData = {
      title: `${showName[status]}学员:`,
      message: `${this.operateName.join(', ')} ?`,
      cancelBtn: true
    };
    this.tools.present(tipsData)
      .then(presentRes => {
        if (presentRes) {
          this.trainService.doAttendance(this.operateParam)
            .subscribe(res => {
              if (res.result === '0') {
                for (const item of this.rollcallData) {
                  if (this.operateParam.idList.indexOf(item.id) > -1) {
                    item.modifyTime = res.data;
                    if (status === 1) {
                      item.status = 1;
                    } else {
                      item.status = 3;
                    }
                  }
                }
                this.tools.showToast(`${showName[status]}成功`);
              } else {
                this.tools.showToast(`${showName[status]}失败`);
              }
              this.allChose = !this.allChose;
              this.operateParam.idList = [];
              this.operateName = [];
            });
        }
      });
  }

  /**
   * @description 获取全选按钮图片
   * @author baoww765
   * @date 2018-01-05
   * */
  allChoseIcon() {
    if (this.disableAllChose) {
      if (this.allChose) {
        return this.getIcon('selected.png');
      } else {
        return this.getIcon('unselect.png');
      }
    } else {
      return this.getIcon('disableSelect.png');
    }
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
    this.searchTerms.unsubscribe();
  }

}





